package com.example.demo.config;

import com.example.demo.dao.UserMapper;
import com.example.demo.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法");
        SimpleAuthorizationInfo Info=new SimpleAuthorizationInfo();
        //Info.addStringPermission("user:add");     //给授权,数据库应该有个权限信息如下：

        //先拿到当前登录的对象
        Subject subject=SecurityUtils.getSubject();
        User user= (User) subject.getPrincipal();//拿到user对象
        Info.addStringPermission(user.getRole());     //设置当前用户的权限
        return Info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证的方法");

        UsernamePasswordToken userToken=(UsernamePasswordToken) token;

        User user=userMapper.queryUserbyname(userToken.getUsername());
        if(user==null){
            return null;              //自动抛出异常UnknownAccountException
        }
        //密码认证,加密传输的密码
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");//这里传user,方便授权的时候取到user
    }
}
